/**
 * Remote channel service for frontend server.
 * Receive push request from backend servers and push it to clients.
 */
let logger = require('pomelo-logger').getLogger(__filename);

module.exports = function(app) {
  return new Remote(app);
};

let Remote = function(app) {
  this.app = app;
};

/**
 * Push message to client by uids.
 *
 * @param  {String}   route route string of message
 * @param  {Object}   msg   message
 * @param  {Array}    sessionIds  user sessionIds that would receive the message
 * @param  {Function} cb    callback function
 */
Remote.prototype.pushMessage = function(route, msg, sessionIds, cb) {
  if(!msg){
    logger.error('Can not send empty message! route : %j, compressed msg : %j',
        route, msg);
    return;
  }

   let connector = this.app.components.__connector__;

  connector.send(null, route, msg, sessionIds, {isPush: true}, function(error) {
    if (!!error) {
       logger.error("push message error=" + error);
    }
    cb(error, []);
  });
};

Remote.prototype.broadcast = function(route, msg, opts, cb) {
  opts = opts || {};
  var connector = this.app.components.__connector__;
  opts.isBroadcast = true;
  connector.send(null, route, msg, null, opts, cb);
};
